package cn.lyjuan.first.netty.demo._3_netty4.client;

import cn.lyjuan.first.netty.demo._3_netty4.server.Server;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

public class Client
{
    public static void main(String[] args) throws InterruptedException
    {
        start();
    }

    public static void start() throws InterruptedException
    {
        Bootstrap boot = new Bootstrap();

        NioEventLoopGroup group = new NioEventLoopGroup();

        // 事件循环组
        boot.group(group);

        // 客户端通道
        boot.channel(NioSocketChannel.class);

        // 处理器
        boot.handler(new ChannelInitializer<SocketChannel>()
        {
            protected void initChannel(SocketChannel ch) throws Exception
            {
                ch.pipeline().addLast(new ClientHandler());
            }
        });

        ChannelFuture future = null;

        try
        {
            // 连接
            future = boot.connect(new InetSocketAddress("127.0.0.1", Server.PORT)).sync();

            // 发送
            future.addListener(new ChannelFutureListener()
            {
                public void operationComplete(ChannelFuture cf) throws Exception
                {
                    if (cf.isSuccess())
                    {
                        String msg = "Hello";
                        cf.channel().writeAndFlush(Unpooled.copiedBuffer(msg, Charset.forName("UTF-8")));
                        System.out.println("client send: " + msg);
                    } else
                    {
                        System.out.println("client connect failed");
                    }
                }
            });
            // 阻塞等待关闭
            future.channel().closeFuture().sync();
        } finally
        {
            group.shutdownGracefully();

        }
    }
}
